package com.srwl.mytx.widget.chatRow;

import android.content.Context;
import android.content.ContextWrapper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.R;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.greendao.MessageDao;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.adapter.MyMessageAdapter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.Calendar;
import java.util.Date;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

public abstract class BaseChatRow extends RecyclerView.ViewHolder {
    protected static final String TAG = BaseChatRow.class.getSimpleName();
    protected String myUserId = "";

    protected LayoutInflater inflater;
    protected Context context;
    protected FragmentActivity activity;
    protected Message message;
    protected User targetUser;
    protected int position;
    protected TextView tv_timestamp;
    protected ImageView iv_avatar;
    protected View bubbleLayout;
    protected ProgressBar progressBar;
    protected ImageView img_status;//信息发送状态图标
    protected TextView tv_status;//回执，已读、未读

    protected MyMessageAdapter.MessageListItemClickListener itemClickListener;
    protected boolean isSendMessage;
    protected MessageDao messageDao;
    protected MyMessageAdapter adapter;

    public BaseChatRow(View itemView) {
        super(itemView);

        initView(itemView);
        messageDao = DBManager.getInstance().getDaoSession().getMessageDao();
    }

    private void initView(View itemView) {
        onInflateView();
        tv_timestamp = itemView.findViewById(R.id.timestamp);
        iv_avatar = itemView.findViewById(R.id.iv_avatar);
        bubbleLayout = itemView.findViewById(R.id.bubble);
        progressBar = itemView.findViewById(R.id.progress_bar);
        img_status = itemView.findViewById(R.id.img_status);
        tv_status = itemView.findViewById(R.id.tv_status);
        onFindViewById(itemView);
    }

    public void setUpView(Context context, Message message, MyMessageAdapter adapter, MyMessageAdapter.MessageListItemClickListener itemClickListener, User targetUser, int position) {
        this.context = context;
        this.message = message;
        this.adapter = adapter;
        this.itemClickListener = itemClickListener;
        this.targetUser = targetUser;
        this.position = position;
        myUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
        isSendMessage = Utils.isSendMessage(message);
        activity = scanForActivity(context);//必须在 onSetUpView方法之前调用，因为这个方法里面，要使用 activity,比如MyChatRowVoice 中就会使用
        setUpBaseView();
        onSetUpView();
        setClickListener();
    }

    private static FragmentActivity scanForActivity(Context cont) {
        if (cont == null)
            return null;
        else if (cont instanceof FragmentActivity)
            return (FragmentActivity) cont;
        else if (cont instanceof ContextWrapper)
            return scanForActivity(((ContextWrapper) cont).getBaseContext());
        return null;
    }

    private void setUpBaseView() {

        if (tv_timestamp != null) {
            if (getAdapterPosition() == 0) {
                tv_timestamp.setText(DateUtils.getTimestampString(message.getCreated()));
                tv_timestamp.setVisibility(VISIBLE);
            } else {
                // show time stamp if interval with last message is > 30 seconds
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.SECOND, -30);
                Date time = calendar.getTime();
                //消息的创建时间在当前时间的30S 以内，不显示时间
                if (this.message.getCreated().after(time)) {
                    tv_timestamp.setVisibility(GONE);
                } else {
                    tv_timestamp.setText(DateUtils.getTimestampString(message.getCreated()));
                    tv_timestamp.setVisibility(VISIBLE);
                }
            }
        }

        String avatarUrl;
        if (isSendMessage) {
            avatarUrl = UserProfileManager.getInstance().getLoginUserInfo().getAvatar();
        } else {
            avatarUrl = targetUser.getAvatar();
        }
        //Glide.with(context).load(avatarUrl).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar_1).dontAnimate().into(iv_avatar);
        GlideLoadUtils.glideLoad(context, avatarUrl, iv_avatar, R.drawable.tx_default_avatar_1);
        if (isSendMessage) {

            tv_status.setVisibility(GONE);
            switch (this.message.getSendState()) {
                case Constant.IM_SEND_STATE_INIT:
                    Log.d(TAG, "消息状态：初始化");
                    progressBar.setVisibility(VISIBLE);
                    img_status.setVisibility(GONE);

                    break;
                case Constant.IM_SEND_STATE_SENDING:
                    Log.d(TAG, "消息状态：发送中");
                    progressBar.setVisibility(VISIBLE);
                    img_status.setVisibility(GONE);
                    break;

                case Constant.IM_SEND_STATE_SUCCESS:
                    //  Log.d(TAG, "消息状态：完成:" + this.message.getId() + ":" + this.message.getContent());
                    progressBar.setVisibility(GONE);
                    img_status.setVisibility(GONE);
                    tv_status.setVisibility(VISIBLE);
                    if (this.message.getReadState() == Constant.MESSAGE_READ_STATE_READ) {
                        tv_status.setText("已读");
                    } else {
                        tv_status.setText("未读");
                    }
                    break;
                case Constant.IM_SEND_STATE_FAIL:
                    Log.d(TAG, "消息状态：发送失败");
                    //如果信息发送失败，显示失败图标
                    progressBar.setVisibility(GONE);
                    img_status.setVisibility(VISIBLE);
                    tv_status.setVisibility(GONE);
                    break;

            }
        }
    }


    private void setClickListener() {
        if (bubbleLayout != null) {
            bubbleLayout.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        //如果监听返回false,说明没消费这个监听，则进入if，在这儿处理
                        if (!itemClickListener.onBubbleClick(message)) {
                            // if listener return false, we call default handling
                            onBubbleClick();
                        }
                    }
                }
            });

            bubbleLayout.setOnLongClickListener(new View.OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onBubbleLongClick(message);
                    }
                    return true;
                }
            });
        }

        if (img_status != null) {
            img_status.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

        if (iv_avatar != null) {
            iv_avatar.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onUserAvatarClick(message.getFromId());
                    }
                }
            });
        }
    }

    public Message getMessage() {
        return message;
    }

    protected abstract void onInflateView();

    /**
     * find view by id
     */
    protected abstract void onFindViewById(View itemView);

    /**
     * refreshMessageList list view when message status change
     */
    protected abstract void onUpdateView();

    /**
     * setup view
     */
    protected abstract void onSetUpView();

    /**
     * on bubble clicked
     */
    protected abstract void onBubbleClick();

    protected ChatRowCallBack chatRowCallBack;

    public void setChatRowCallBack(ChatRowCallBack chatRowCallBack) {
        this.chatRowCallBack = chatRowCallBack;
    }

    public interface ChatRowCallBack {

        void onMessageRead(Message message);

        void onAudioPlayCompletion(int position);

        void onFileMessageDownLoadComplete(int position);
    }

}
